package com.gwz.sys.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gwz.sys.constast.SYSConstast;
import com.gwz.sys.domain.Dept;
import com.gwz.sys.service.DeptService;
import com.gwz.sys.utils.DataGridView;
import com.gwz.sys.utils.ResultObj;
import com.gwz.sys.utils.TreeNode;
import com.gwz.sys.vo.DeptVo;

@RestController
@RequestMapping("dept")
public class DeptController {
	
	@Autowired
	private DeptService deptService;
	
	@RequestMapping("loadDeptLeftTreeJson")
	public List<TreeNode> loadDeptLeftTreeJson(DeptVo deptVo){
		deptVo.setAvailable(SYSConstast.SYS_AVAILABLE_TRUE);
		List<Dept> list = deptService.queryAllDeptForList(deptVo);
		List<TreeNode> treeNodes = new ArrayList<>();
		for (Dept dept : list) {
			Boolean open = dept.getOpen() == SYSConstast.SYS_OPEN_TRUE?true:false;
			Boolean isParent = dept.getParent() == SYSConstast.SYS_PARENT_TRUE?true:false;
			treeNodes.add(new TreeNode(dept.getId(), dept.getPid(), dept.getName(), open, isParent));
		}
		return treeNodes;
	}
	
	
	@RequestMapping("loadAllDept")
	public DataGridView loadAllDept(DeptVo deptVo) {
		return deptService.queryAllDept(deptVo);
	}
	
	@RequestMapping("loadMaxOrderNumber")
	public Integer loadMaxOrderNumber() {
		return deptService.queryMaxOrderNumber()+1;
	} 
	
	@RequestMapping("addDept")
	public ResultObj addDept(DeptVo deptVo) {
		ResultObj resultObj = new ResultObj(200, "添加成功");
		try {
			deptService.addDept(deptVo);
			return resultObj;
		} catch (Exception e) {
			resultObj.setCode(-1);
			resultObj.setMsg("添加失败");
			e.printStackTrace();
			return resultObj;
		}
	}
	
	@RequestMapping("updateDept")
	public ResultObj updateDept(DeptVo deptVo) {
		ResultObj resultObj = new ResultObj(200, "修改成功");
		try {
			deptService.updateDept(deptVo);
			return resultObj;
		} catch (Exception e) {
			resultObj.setCode(-1);
			resultObj.setMsg("修改失败");
			e.printStackTrace();
			return resultObj;
		}
	}
	
	@RequestMapping("CurrentIsChidren")
	public ResultObj CurrentIsChidren(DeptVo deptVo) {
		Integer count = deptService.CurrentIsChidren(deptVo.getId());
		if (count>0) {
			return new ResultObj(-1,"该部门下面有子部门，请先删除子部门");
		}
		return new ResultObj(200,"");
	}
	
	@RequestMapping("deleteDept")
	public ResultObj deleteDept(DeptVo deptVo) {
		ResultObj resultObj = new ResultObj(200, "删除成功");
		try {
			deptService.deleteDept(deptVo.getId());
			return resultObj;
		} catch (Exception e) {
			resultObj.setCode(-1);
			resultObj.setMsg("删除失败");
			e.printStackTrace();
			return resultObj;
		}
	}
	
}
